package codingforgreat.class14;

public class Class01_Parentheses {
    public int longestValidParentheses(String s) {
        if (s == null || s.length() < 2) {
            return 0;
        }
        int ans = 0;
        int pre = 0;
        char[] str = s.toCharArray();
        int[] dp = new int[str.length];
        for (int i = 1; i < str.length; i++) {
            if(str[i] == ')'){
                pre = i - dp[i - 1] - 1;//上一个(位置
                if(pre >= 0 && str[pre] == '('){
                dp[i] = dp[i - 1] + 2 + (pre > 0 ? dp[pre - 1] : 0);
                }

            }
            ans = Math.max(ans,dp[i]);
        }
        return ans;
    }
}
